package com.ciccwm.dubbo.filter;

import com.ciccwm.core.exception.ValidationException;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.rpc.Filter;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.Result;
import org.apache.dubbo.rpc.RpcException;

import jakarta.validation.ConstraintViolation;
import jakarta.validation.Validation;
import jakarta.validation.Validator;
import jakarta.validation.ValidatorFactory;
import java.util.Set;

/**
 * Dubbo参数校验过滤器.
 */
@Slf4j
@Activate(group = CommonConstants.PROVIDER)
public class DubboValidationFilter implements Filter {
    private final Validator validator;

    /**
     * 构造函数.
     */
    public DubboValidationFilter() {
        ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
        this.validator = factory.getValidator();
    }

    @Override
    public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
        Object[] arguments = invocation.getArguments();
        if (arguments != null && arguments.length > 0) {
            for (Object arg : arguments) {
                if (arg != null) {
                    Set<ConstraintViolation<Object>> violations = validator.validate(arg);
                    if (!violations.isEmpty()) {
                        throw new ValidationException("Parameter validation failed: " + violations);
                    }
                }
            }
        }
        return invoker.invoke(invocation);
    }
} 
